//
// Created by 崔世强 on 2018/4/2.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation
import SwiftyJSON

class ChangeMasterHandler: NoticeHandlerProtocol {
    static let instance = ChangeMasterHandler()

    private init() {
    }

    func handler(_ msg: Message) {

    }

    func show(_ msg: ChatMessage) -> String? {
        do {
            let contact = try ContactDao.getContact(msg.from)
            let groupMember = try GroupDao.getMember(msg.sessionId, userId: msg.from)

            let json = JSON(parseJSON: msg.text ?? "")

            let userId = json["userId"].intValue
            let masterMember = try GroupDao.getMember(msg.sessionId, userId: userId)
            let masterUser = try ContactDao.getContact(userId)

            var masterName = masterUser?.remarkName ?? masterMember?.nickName ?? contact?.name
//            if masterUser?.me {
//                masterName = "你"
//            }

            var name = contact?.remarkName ?? groupMember?.nickName ?? contact?.name
            if msg.isMe {
                name = "你"
            }
            return (masterUser?.me ?? false) ? "你成为了群主" : "群主变更为\(masterName ?? "陌生人(已退群)")"

        } catch {
            return msg.text
        }
    }
}
